<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>二进制格式的文件上传</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script>
  "use strict"; {
    // https://www.bilibili.com/video/BV1mn3ye4EHF/?spm_id_from=pageDriver&vd_source=c78fd23f2edd9e3deea8f1267be4aaab
    function uploadBinary(file, onProgress, onFinish) {
      const XHR = new XMLHttpRequest()

      // 请求完成后
      XHR.onload = () => {
        let resp = JSON.parse(XHR.responseText);
        onFinish(resp)
      }

      // 请求进度
      XHR.upload.onprogress = e => {
        let percent = Math.floor((e.loaded / e.total) * 100)
        onProgress(percent)
      }

      XHR.open("post", "http://xxx.com/upload/binary")

      // 设置二进制请求头格式
      XHR.setRequestHeader("content-type", "application/octet-stream");
      let ext = String(file.name.split(".").pop())
      XHR.setRequestHeader("ext", ext)

      // 发送请求
      XHR.send(file)

      return function () {
        XHR.abort()
      }
    }
  };
</script>

</html>